<template>
  <table class="table">
    <thead>
      <tr>
        <th class="cell" v-for="v in tableHead" :key="v.prop">
          {{v.label}}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(item,i) in tableData" :key="i">
        <td class="cell tdCell" v-for="v in tableHead" :key="v.prop" @click.stop="tdClick($event,item,i,v)">
          {{item[v.prop]}}
        </td>
      </tr>
    </tbody>
  </table>
</template>
<script setup>
  import {createApp, reactive} from "vue"
  import MyInput from "./MyInput.vue"
  
  const props = defineProps({
    tableHead: {
      type: Array,
      default: []
    },
    tableData: {
      type: Array,
      default: []
    }
  })
  const emit = defineEmits(["changeData"])

  const data = reactive({
    prop:"",
    index:-1,
    value: ""
  })

  const setData = ({prop="",value="",index=-1}) => {
    data.prop = prop
    data.value = value
    data.index = index
  }


  let createInput
  const removeCreateInput = (app) => {
    app.unmount()
  }


  const setValue = (value) => {
    data.value = value
    emit("changeData",{...data})
    setData({prop:"",value:"",index:-1})
  }
  
  const tdClick = (e,item,i,v) => {
    const value = item[v.prop]
    setData({prop:v.prop,value:value,index:i})

    createInput && removeCreateInput(createInput)

    const target = e.target
    const fragment = document.createDocumentFragment()
    createInput = createApp(MyInput,{
      text: value,
      setValue,
    })
    createInput.mount(fragment)
    target.appendChild(fragment)
  }
  
  window.addEventListener('click',()=>{
    createInput && removeCreateInput(createInput)
  })
</script>
<style>
.table {
  width: 100%;
}
.cell {
  padding: 8px 16px;
}
.tdCell {
  text-align: center;
  cursor: pointer;
  position: relative;
}
</style>